package com.tom.demo.component;

import com.tom.demo.common.constant.CacheConstants;
import com.tom.demo.common.entity.SysUser;
import com.tom.demo.common.utils.RedisUtil;
import com.tom.demo.mapper.SysMenuMapper;
import com.tom.demo.mapper.SysRoleMapper;
import com.tom.demo.mapper.SysUserMapper;
import com.tom.demo.security.DetailsUser;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class EnvironmentComponent implements ApplicationListener<ApplicationStartedEvent> {

    @Resource
    private Environment environment;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onApplicationEvent(@NotNull ApplicationStartedEvent event) {
        //检测当前是否是开发环境
        String[] activeProfiles = environment.getActiveProfiles();
        if(Arrays.asList(activeProfiles).contains("dev")) {
            SysUser sysUser = sysUserMapper.findByUserName("admin");
            Set<String> roles = sysRoleMapper.findByRoleKey(null);
            Set<String> permissions = sysMenuMapper.findByPerms(null);
            //特殊处理一下角色，加上固定前缀，security底层规定
            Set<String> rolesKeys = roles.stream().map(roleKey -> "ROLE_" + roleKey).collect(Collectors.toSet());
            //把数据封装成UserDetails
            DetailsUser detailsUser = new DetailsUser(sysUser, rolesKeys, permissions);
            //设置到redis,并且不过期
            redisUtil.setCacheObject(CacheConstants.GLOBAL_LOGIN_TOKEN_KEY,detailsUser);
        }
    }
}
